clear all

** frame to hold bootstrap results 
local glist ami appendicitis cancer fracture labor_delivery other_accident ///
	stroke vehicle_accident wound
local B 500

capture frame drop bs_ests 
frame create bs_ests  
frame bs_ests {
	clear 
	local obs = wordcount("`glist'")
	set obs `obs'

	foreach v in test_rate pos_rate n {
		gen `v' = . 
	}
	gen group = ""

	tokenize `glist' 
	forvalues g = 1/`obs' {
		replace group = "``g''" in `g'
	}
	expand `B'+1
	bysort group: gen iter = _n-1
	sort group iter 
}


* pre set data to speed up bootstrap
timer clear 1 
timer on 1
qui foreach g of local glist {
	use health/inp_clean if `g'==1 & admit_date >= mdy(3,13,2020), clear
				
	keep test_tight pos_tight
	save health/inp_`g', replace 

}


timer clear 1 
timer on 1
** loop groups and bootstrap iterations
local row = 0 
qui foreach g of local glist {
	noi di "on `g' ($S_TIME) "
	forvalues bs =  0/`B' {
		* load the data and bsample
		use health/inp_`g', clear
		if `bs' > 0 bsample 
		
		** test rate and positvity rate
		local ++row
		sum test_tight
		frame bs_ests: replace test_rate = r(mean) in `row'
		frame bs_ests: replace n = r(N) in `row'
		sum pos_tight 
		frame bs_ests: replace pos_rate = r(mean) in `row'
		frame bs_ests: assert iter[`row'] == `bs'
	}
}
timer off 1
timer list 1 

clear
cwf bs_ests
sum
save tables/bounds_by_cause_bs, replace 
